package noth.li;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * MyFileUtils继承了apache的FileUtils
 * 重新写了其中的copyFileToDirectory方法
 * 重写后的copyFIleToDirectory方法支持从文件拷贝到文件中去
 */
public class MyFileUtils extends FileUtils {

    private static final long FILE_COPY_BUFFER_SIZE = ONE_MB * 30;

    public static void myCopyFileToDirectory(final File srcFile, final File destDir, final boolean preserveFileDate)
            throws IOException {
        System.out.println("MyFile源文件===>"+srcFile);
        System.out.println("MyFile目的地===>"+destDir);
        myDoCopyFile(srcFile, destDir, preserveFileDate);
    }

    /**
     * 由于继承重写之后,doCopyFile是私有方法,不支持重写,所以只能复制一份
     * @param srcFile
     * @param destFile
     * @param preserveFileDate
     * @throws IOException
     */
    private static void myDoCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate)
            throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }

        try (FileInputStream fis = new FileInputStream(srcFile);
             FileChannel input = fis.getChannel();
             FileOutputStream fos = new FileOutputStream(destFile);
             FileChannel output = fos.getChannel()) {
            final long size = input.size(); // TODO See IO-386
            long pos = 0;
            long count = 0;
            while (pos < size) {
                final long remain = size - pos;
                count = remain > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : remain;
                final long bytesCopied = output.transferFrom(input, pos, count);
                if (bytesCopied == 0) { // IO-385 - can happen if file is truncated after caching the size
                    break; // ensure we don't loop forever
                }
                pos += bytesCopied;
            }
        }

        final long srcLen = srcFile.length(); // TODO See IO-386
        final long dstLen = destFile.length(); // TODO See IO-386
        if (srcLen != dstLen) {
            throw new IOException("Failed to copy full contents from '" +
                    srcFile + "' to '" + destFile + "' Expected length: " + srcLen + " Actual: " + dstLen);
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }
}
